package com.code.mail;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 邮件发送服务类
 *
 * @author wwei
 * @date 2019/5/16
 */
@Service
public class MailService {

    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String autoMailUser;

    public MailService(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    void sentMail(String sender, String receiver, String subject, String context) {

        SimpleMailMessage message = new SimpleMailMessage();
        //如果发送者邮箱为空，则用默认用户
        if ( StringUtils.isEmpty(sender)){
            message.setFrom(autoMailUser);
        }else {
            message.setFrom(sender);
        }
        message.setTo(receiver);
        message.setSubject(subject);
        message.setText(context);

        mailSender.send(message);
    }
}
